//
//  LYOAuthViewController.swift
//  微博
//
//  Created by liuerying on 16/5/22.
//  Copyright © 2016年 liuerying. All rights reserved.
//

import UIKit

import SVProgressHUD
//偏好设置保存的key
//private let userInfoKey = "com.baidu.userInfoKey"

class LYOAuthViewController: UIViewController{
    //声明一个webView属性
    let webView = UIWebView()
    override func loadView() {
        view = webView
        //当网络差的时候,webView会出现黑条,这句话避免出现黑条
        webView.opaque = false
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        
        setNavBar()
    
        loadOauthPage()
    
        
    }

    func loadOauthPage(){
    
        let urlStr = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string: urlStr)!
        
        let request = NSURLRequest(URL: url)
//        print(request)
        webView.loadRequest(request)
        
    
    }

 
}

extension LYOAuthViewController{
    //导航条 关闭 按钮的设置
    private func setNavBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem( title: "关闭", target: self, action: #selector(LYOAuthViewController.close))
        
    }
    //点击关闭按钮事件
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
        
    }
}


extension LYOAuthViewController : UIWebViewDelegate {

    //webView开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        //显示用户等待指示器
        SVProgressHUD.show()
        
    }
    
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        //隐藏用户等待指示器
        SVProgressHUD.dismiss()
    }
    
    //将要开始加载请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
      
//        print(request)
        
        //获取请求的URL中的数据 绝对的
        let urlStr = request.URL?.absoluteString ?? ""
        
        let successFlag = "code="
        //判断如果字符串中包含code= 就说明授权成功
        if urlStr.containsString(successFlag){
        
            let range = urlStr.rangeOfString(successFlag)!
            let code = urlStr.substringFromIndex(range.endIndex)
//            print(code,urlStr)
            
          LYUserAccountModel.sharedAccountViewModel.loadAccessToken(code, finished: { (isSuccess) in
            if !isSuccess{
            SVProgressHUD.showErrorWithStatus(AppErrorTip)
                return
                
            }
            
            NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewController, object: nil)
            
          })
//
            return false
        }
        
        return true
        
    }
    
}

        
        
        
        
